package com.study.testSpringBoot.interceptor.testController;

import java.sql.SQLException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.study.testSpringBoot.util.ReturnMsg;


@RestControllerAdvice
public class ExceptionHandlerAdvice {

	private Logger logger = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);
	
	@ExceptionHandler
    public ReturnMsg handler(HttpServletRequest req, HttpServletResponse res, Exception e) {
        logger.info("Restful Http请求发生异常...");

        if (res.getStatus() == HttpStatus.BAD_REQUEST.value()) {
            logger.info("修改返回状态值为200");
            res.setStatus(HttpStatus.OK.value());
        }

        if (e instanceof NullPointerException) {
            logger.error("代码00：" + e.getMessage(), e);
            return ReturnMsg.fail("发生空指针异常");
        } else if (e instanceof IllegalArgumentException) {
            logger.error("代码01：" + e.getMessage(), e);
            return ReturnMsg.fail("请求参数类型不匹配");
        } else if (e instanceof SQLException) {
            logger.error("代码02：" + e.getMessage(), e);
            return ReturnMsg.fail("数据库访问异常");
        } else {
        	String localizedMessage = e.getLocalizedMessage();
        	String message = e.getMessage();
        	StackTraceElement[] stackTrace = e.getStackTrace();
        	Arrays.stream(stackTrace).forEach(System.out::println);
        	Throwable[] suppressed = e.getSuppressed();
            logger.error("代码99：" + e.getMessage(), e);
            return ReturnMsg.fail("服务器代码发生异常,请联系管理员");
        }
    }
}
